/*******************************************************************************
 * Software Name : Android Simple Downloader
 *
 * Copyright © 2012 Rinvay Tang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package com.rinvay.network.http.conn;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

import com.rinvay.network.access.NetworkAccessState;
import com.rinvay.network.http.HttpRequest;
import com.rinvay.network.http.conn.impl.DefaultHttpConnectionListener;
import com.rinvay.network.http.exception.ErrorMessage;
import com.rinvay.network.http.exception.NetWorkInvalidException;
import com.rinvay.utils.logger.Log;

/**
 * Http 连接类
 * @author rinvay
 * @date 2012-3-10
 */
public abstract class HttpConnection implements Runnable
{
    private static final String TAG = "HttpConnection";

    private String name = "";

//    protected int httpConnectionState = -1;

    protected HttpRequest request = null;

    protected HttpConnectionListener listener = null;
    
    
//----------------------------------------------------------------
    protected HttpURLConnection conn = null;

    protected InputStream in = null;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void run() {
//        httpConnectionState = CONNECTION_STATE_CONNECTING;
//        if (listener != null) {
//            listener.onConnecting();
//        }
        
        boolean hasException = false;
        //开始连接
        try {
            connect();
        } catch (NetWorkInvalidException e) {
            e.printStackTrace();
            hasException = true;
            if (listener != null) {
                listener.onError(ErrorMessage.ERROR_CODE_NETWORK_INVALID, null);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            hasException = true;
            if (listener != null) {
                listener.onError(ErrorMessage.ERROR_CODE_MALFORMED_URL, null);
            }
        } catch (IOException e) {
            hasException = true;
            e.printStackTrace();
            if (listener != null) {
                listener.onError(ErrorMessage.ERROR_CODE_OPEN_CONNECTION, null);
            }
        } catch (Exception e) {
            hasException = true;
            e.printStackTrace();
            if (listener != null) {
                listener.onError(ErrorMessage.ERROR_CODE_OPEN_CONNECTION, null);
            }
        } finally {
            if(hasException) {
                close();
                handleConnectingFail();
                return;
            }
        }
        
        //已连接
//        httpConnectionState = CONNECTION_STATE_CONNECTED;
        if (listener != null) {
            listener.onConnected();
        }
        
        try {
            //发送数据
            if (request.getData() != null && request.getData().length > 0) {
                sendData(request.getData());
            }

            //服务器响应
            int responseCode = conn.getResponseCode();
            if (responseCode / 100 == 2) {
                handleResponse(getInputStream());
            } else {
                if (listener != null) {
                    listener.onError(ErrorMessage.ERROR_SERVER_UNEXPECTED_RESP, responseCode + "");
                }
            }

       
        } catch (IOException e) {
            e.printStackTrace();
            if (listener != null) {
                listener.onError(ErrorMessage.ERROR_WRITE_READ_DATA, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (listener != null) {
                listener.onError(ErrorMessage.ERROR_WRITE_READ_DATA, null);
            }
        } finally {
//            httpConnectionState = CONNECTION_STATE_FINISH;
            close();
            handleConnectionFinished();
        }
        
    }

    /**
     * open connection to url
     * @throws MalformedURLException 
     * @throws IOException 
     * @throws NetWorkInvalidException 
     */
    public HttpURLConnection connect() throws MalformedURLException,
            IOException, NetWorkInvalidException {
        Log.i(TAG, name + " connect");
        if (!NetworkAccessState.isNetWorkValid()) {
            Log.i(TAG, "NetWorkInvalid");
            throw new NetWorkInvalidException();
        }

        //MalformedURLException: a MalformedURLException may be thrown here 
        URL url = new URL(request.getUrl());

        //a IOException may be thrown here eg:UnknownHostException
        try {
            conn = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        //a IOException may be thrown here eg:ProtocolException, but it's unusual
        conn.setRequestMethod(request.getMethod());

        if ("POST".equalsIgnoreCase(request.getMethod())) {
            conn.setDoInput(true);
            conn.setDoOutput(true);
        }

        HashMap<String, String> headers = request.getHeaders();
        if (headers != null) {
            Set<Entry<String, String>> entries = headers.entrySet();
            Iterator<Entry<String, String>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = iterator.next();
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }

        //IOException: A SocketTimeoutException is thrown if the connection could not be established when connect()
        conn.setConnectTimeout(60 * 1000);
        //IOException  A SocketTimeoutException is thrown if the connection could not be established when connect()
        conn.setReadTimeout(60 * 1000);

        try {
            conn.connect();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        Log.i(TAG, name + " connected");
        return conn;
    }

    /**
     * post data while POST request
     * @param data
     * @throws IOException
     */
    protected void sendData(byte[] data) throws IOException {
        OutputStream os = conn.getOutputStream();
        os.write(data);
        os.flush();
        os.close();
    }

    /**
     * get response inputstream
     * @return
     * @throws IOException
     */
    public InputStream getInputStream() throws IOException {
        in = conn.getInputStream();
        return in;
    }
    
    /**
     * close stream and connection
     */
    public void close() {
        try {
            if (in != null) {
                in.close();
                in = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }

    }
    
    /**
     * 处理服务器连接失败
     */
    public abstract void handleConnectingFail();
    /**
     * 处理服务器回应
     * @param in
     * @throws IOException
     */
    public abstract void handleResponse(InputStream in) throws IOException;
    /**
     * 处理服务器连接结束
     */
    public abstract void handleConnectionFinished();

    
    protected static final int CONNECTION_STATE_CONNECTING = 0;
    protected static final int CONNECTION_STATE_CONNECTED = CONNECTION_STATE_CONNECTING + 1;
    protected static final int CONNECTION_STATE_FINISH = CONNECTION_STATE_CONNECTED + 1;

}
